package com.ytjj.qmyx.mall.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.ytjj.common.enums.ErrorMsgStatusEnum;
import com.ytjj.common.exception.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 *  *
 **/
@Slf4j
@Component
public class AliyunSmsUtil {

    //aliyun:
    //  access-id: ************
    //  access-key: **********
    //  sms:
    //    url: dysmsapi.aliyuncs.com #阿里短信url
    //    product: Dysmsapi #阿里产品名称,短信业务
    //    sign-name: *** #阿里短信签名
    //    template-id:
    //      register: SMS_1865**** #用户注册
    //      login: SMS_18638**** #登录

    /**
     * 阿里账号app key
     */
    @Value("${aliyun.access-id}")
    private static String accessId;

    /**
     * 阿里账号app secret
     */
    @Value("${aliyun.access-key}")
    private static String accessKey;

    /**
     * 产品业务名称
     */
    @Value("${aliyun.sms.product}")
    private static String product;

    /**
     * 阿里云短信发送域名
     */
    @Value("${aliyun.sms.url}")
    private static String domain;

    /**
     * 短信签名
     */
    @Value("${aliyun.sms.sign-name}")
    private static String signName;

    /**
     * 1短信模板-付款成功
     */
    @Value("${aliyun.sms.template-id.pay}")
    private static String paySuccess;
    /**
     * 2短信模板-验证码
     */
    @Value("${aliyun.sms.template-id.code}")
    private static String verCode;


    /**
     * 统一发送验证码
     */
    public static boolean sendSms(String phone, Integer type, String code) {
        switch (type) {
            //支付成功
            case 1:
                return sendSmsTo(phone, paySuccess, "");
            //验证码
            case 2:
                Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
                Matcher isNum = pattern.matcher(code);
                if (!isNum.matches()) {
                    throw new ApiException(ErrorMsgStatusEnum.VERIFY_CODE_ERROR.getMsg());
                }
                JSONObject tempParam = new JSONObject();
                tempParam.put("code", code);
                return sendSmsTo(phone, verCode, tempParam.toJSONString());
            default:
                return false;
        }
    }

    /**
     * 发送验证
     *
     * @return
     */
    public static boolean sendSmsTo(String phone, String tempCode, String tempParam) {
        log.info("\n\n\n统一发送短信参数------>phone：{},tempCode:{},tempParam:{}", phone, tempCode, tempParam);
        SendSmsResponse sendSmsResponse = null;
        try {
            sendSmsResponse = send(phone, tempCode, tempParam);
        } catch (ClientException e) {
            e.printStackTrace();
            throw new ApiException(ErrorMsgStatusEnum.SEND_FAIL.getMsg());
        }
        log.info("\n\n\n统一发送短信报文------>" + JSONObject.toJSONString(sendSmsResponse) + "\n\n\n");
        if ("OK".equals(sendSmsResponse.getCode())) {
            return true;
        }
        //短信发送限制
        if ("isv.BUSINESS_LIMIT_CONTROL".equalsIgnoreCase(sendSmsResponse.getCode())) {
            String permits = sendSmsResponse.getMessage().split(":")[1];
            if ("1".equals(permits)) {
                throw new ApiException(ErrorMsgStatusEnum.VERIFY_CODE_MIN_LIMIT.getMsg());
            }
            if ("5".equals(permits)) {
                throw new ApiException(ErrorMsgStatusEnum.VERIFY_CODE_HOUR_LIMIT.getMsg());
            }
            if ("10".equals(permits)) {
                throw new ApiException(ErrorMsgStatusEnum.VERIFY_CODE_DAY_LIMIT.getMsg());
            }
        }
        //发送错误
        if ("isv.MOBILE_NUMBER_ILLEGAL".equalsIgnoreCase(sendSmsResponse.getCode())) {
            throw new ApiException(ErrorMsgStatusEnum.PHONE_ERROR.getMsg());
        }
        if ("isv.AMOUNT_NOT_ENOUGH".equalsIgnoreCase(sendSmsResponse.getCode())
                || "isv.OUT_OF_SERVICE".equalsIgnoreCase(sendSmsResponse.getCode())
                || "isp.RAM_PERMISSION_DENY".equalsIgnoreCase(sendSmsResponse.getCode())) {
            //账户余额不足,业务停机,RAM权限DENY
            throw new ApiException(ErrorMsgStatusEnum.SEND_ERROR.getMsg());
        }
        //账户余额不足,业务停机,RAM权限DENY
        throw new ApiException(JSONObject.toJSONString(sendSmsResponse));
    }


    public static SendSmsResponse send(String phone, String tempCode, String tempParam) throws ClientException {
        //可自助调整超时时间
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");

        //初始化acsClient,暂不支持region化
        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessId, accessKey);
        DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
        IAcsClient acsClient = new DefaultAcsClient(profile);

        //组装请求对象-具体描述见控制台-文档部分内容
        SendSmsRequest request = new SendSmsRequest();
        //必填:待发送手机号
        request.setPhoneNumbers(phone);
        //必填:短信签名-可在短信控制台中找到
        request.setSignName(signName);
        //必填:短信模板-可在短信控制台中找到
        request.setTemplateCode(tempCode);
        //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
        request.setTemplateParam(tempParam);

        //选填-上行短信扩展码(无特殊需求用户请忽略此字段)
        //request.setSmsUpExtendCode("90997");

        //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
        request.setOutId(UUID.randomUUID().toString());

        //hint 此处可能会抛出异常，注意catch
        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        return sendSmsResponse;
    }

    //com.aliyun:aliyun-java-sdk-core:4.4.9
    //com.aliyun:aliyun-java-sdk-dysmsapi:2.1.0

//    public static void main(String[] args) throws Exception {
//        boolean b = AliyunSmsUtil.sendSms("13627280350", 1, "YX5687");
//        System.out.println(b);
//    }
}
